package com.easyclearance.countryRegUtil;

import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.SSLContext;
import javax.net.ssl.X509TrustManager;

import org.apache.log4j.Logger;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.stereotype.Repository;

import com.alibaba.fastjson2.JSONObject;
@Repository
public class MalaysiaMadcRegUtil {
	
	Logger logger = Logger.getLogger(MalaysiaMadcRegUtil.class);
	
    private static String registerMainUrl = "https://imigresen-online.imi.gov.my/mdac/main?registerMain";
    private static String registerUrl = "https://imigresen-online.imi.gov.my/mdac/register";

    private static String userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36";

    private static SSLContext context = null;

    
    /**
     * 绕过HTTPS验证
     */
    public SSLContext getContext() {
        if(context == null) {
            initContext();
            
        }
        return context;
    }

    /**
     * 绕过HTTPS验证
     */
    private synchronized void initContext(){
        try {
            context = SSLContext.getInstance("TLS");
            context.init(null, new X509TrustManager[]{new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                }

                @Override
                public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                }

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[0];
                }
            }}, new SecureRandom());
        } catch (NoSuchAlgorithmException e) {
        } catch (KeyManagementException e) {
        }
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
	public Map<String,Map<String,String>> getInitParams() throws Exception{
        Map params = new HashMap();
        Connection.Response response = Jsoup.connect(registerMainUrl)
                .sslSocketFactory(getContext().getSocketFactory())
                .timeout(20000).method(Connection.Method.GET).execute();

        Document doc = response.parse();
        Element body = doc.body();
        Element _sourcePage = body.selectFirst("input[name=_sourcePage]");
        Element __fp = body.selectFirst("input[name=__fp]");

        Map hiddenParams = new HashMap();
        hiddenParams.put("_sourcePage",_sourcePage.attr("value"));
        hiddenParams.put("__fp",__fp.attr("value"));
        params.put("params",hiddenParams);

        Map<String,String> cookies = response.cookies();
        params.put("cookies",cookies);

        return params;
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
	public boolean doregister(Map<String,String> cookies,Map params) throws Exception{
        Connection connection = Jsoup.connect(registerUrl)
                .userAgent(userAgent)
                .referrer(registerMainUrl)
                .header("Accept-Encoding","gzip, deflate, br")
                .header("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7")
                .sslSocketFactory(getContext().getSocketFactory())
                .timeout(20000)
                .method(Connection.Method.POST);
        if(null != cookies){
            connection.cookies(cookies);
        }
        if(null != params) {
            connection.data(params);
        }

        Connection.Response response = connection.execute();
//        Document doc = response.parse();
//        System.out.println("响应："+doc);
        URL resUrl = response.url();
        if(resUrl != null){
            System.out.println(resUrl.toString().indexOf("SUCCESSFULLY"));
            return resUrl.toString().indexOf("SUCCESSFULLY") >0 ? true : false;
        }
        return false;
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
	public boolean register(Map userParams){
    	System.out.println("请求参数："+JSONObject.toJSONString(userParams));
        try {
            Map<String,Map<String,String>> params = new MalaysiaMadcRegUtil().getInitParams();
            params.get("params").putAll(userParams);
            return doregister(params.get("cookies"), params.get("params"));
        } catch (Exception e) {

        }
        return false;
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
	protected  static void testRegister(){
        Map userParams = new HashMap();
        userParams.put("mdacVisaCountry","ALL");
        userParams.put("hdCurrLang","ms");
        userParams.put("name","XIAO NI");
        userParams.put("passNo","E26931367");
        userParams.put("dob","04/10/1981");
        userParams.put("nationality","CHN");
        userParams.put("sex","2");
        userParams.put("passExpDte","29/07/2024");
        userParams.put("email","travbao@163.com");
        userParams.put("confirmEmail","travbao@163.com");
        userParams.put("region","86");
        userParams.put("confirmRegion","86");
        userParams.put("mobile","13811110516");
        userParams.put("confirmMobile","13811110516");
        userParams.put("arrDt","16/03/2024");
        userParams.put("depDt","19/03/2024");
        userParams.put("trvlMode","1");
        userParams.put("embark","CHN");
        userParams.put("vesselNm","SN123");
        userParams.put("accommodationStay","01");
        userParams.put("accommodationAddress1","SWAN GARDEN HOTEL MELAKA, 1, JINKSB 1, TAMAN KOTA");
        userParams.put("accommodationAddress2","");
        userParams.put("accommodationState","01");
        userParams.put("accommodationPostcode","80000");
        userParams.put("accommodationCity","0100");
        userParams.put("submitRegistration","Submit");

        new MalaysiaMadcRegUtil().register(userParams);
        //mdacVisaCountry: ALL
        //hdCurrLang: ms
        //name: XIONG+GUOFENG
        //passNo: E68382458
        //dob: 09%2F06%2F1986
        //nationality: CHN
        //sex: 1
        //passExpDte: 15%2F02%2F2026
        //email: 1624338898%40qq.com
        //confirmEmail: 1624338898%40qq.com
        //region: 86
        //confirmRegion: 86
        //mobile: 13811110516
        //confirmMobile: 13811110516
        //arrDt: 22%2F02%2F2024
        //depDt: 22%2F02%2F2024
        //trvlMode: 1
        //embark: CHN
        //accommodationStay: 01
        //accommodationAddress1: SWAN+GARDEN+HOTEL+MELAKA%2C+1%2C+JINKSB+1%2C+TAMAN+KOTA
        //accommodationAddress2:
        //accommodationState: 04
        //accommodationPostcode: 75200
        //accommodationCity: 0411
    }

    public static void main(String[] args) {
    	
//    	String aaString = "{\"accommodationState\":\"14\",\"confirmMobile\":\"13811110516\",\"depDt\":\"09/04/2024\",\"confirmRegion\":\"86\",\"accommodationCity\":\"1401\",\"passNo\":\"EK8030268\",\"passExpDte\":\"10/08/2033\",\"arrDt\":\"08/04/2024\",\"email\":\"3677928797@qq.com\",\"accommodationStay\":\"01\",\"accommodationAddress1\":\"DAYS HOTEL KOMPLEKS METRO, FRASER BUSINESS PARK, 1, JALAN METRO PUDU 2, PUDU\",\"submitRegistration\":\"Submit\",\"mdacVisaCountry\":\"ALL\",\"sex\":\"2\",\"embark\":\"CHN\",\"mobile\":\"13811110516\",\"accommodationPostcode\":\"3677928797@qq.com\",\"confirmEmail\":\"3677928797@qq.com\",\"hdCurrLang\":\"ms\",\"nationality\":\"CHN\",\"vesselNm\":\"CZ5049\",\"dob\":\"10/08/2033\",\"trvlMode\":\"1\",\"name\":\"GONG XIAOLEI\",\"region\":\"86\",\"accommodationAddress2\":\"\"}";
//        try {
//        	Map parseObject = JSONObject.parseObject(aaString,Map.class);
//        	parseObject.put("accommodationPostcode", "55000");
////        	MalaysiaMadcRegUtil.testRegister();
//            boolean register = new MalaysiaMadcRegUtil().register(parseObject);
//            System.out.println(register);
//        }catch (Exception e){
//            e.printStackTrace();
//        }
    }
}
